package com.yanjr.modules.sys.dao.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Repository;

import com.yanjr.common.Constants;
import com.yanjr.common.persistence.BaseDaoImpl;
import com.yanjr.modules.sys.dao.RoleDao;
import com.yanjr.modules.sys.entity.Menu;
import com.yanjr.modules.sys.entity.Office;
import com.yanjr.modules.sys.entity.Role;

@Repository("roleDao")
public class RoleDaoImpl extends BaseDaoImpl<Role> implements RoleDao {

	@Override
	public Role findByName(String name) {
		String sql = "select * from sys_role where useable=? and name=?";
		return super.findOne(sql, new Object[] {Constants.DEL_FLAG_NORMAL, name});
	}

	@Override
	public List<Role> findAllList() {
		String sql = "select * from sys_role where del_flag=?";
		return findList(sql, new Object[] {Constants.DEL_FLAG_NORMAL});
	}

	@Override
	public List<Role> findByUserId(String userId) {
		String sql = "select * from sys_role r join sys_user_role ur on r.id=ur.role_id where ur.user_id=? ";
		return super.findList(sql, new Object[] {userId});
	}

	@Override
	public void batchUpdateRoleAndMenu(final String roleId, final List<Menu> list) {
		//1: delete 
		String sql1 = "delete from sys_role_menu where role_id=?";
		super.jdbcTemplate.update(sql1, roleId);
		//2: insert
		String sql2 = "insert into sys_role_menu (role_id, menu_id) values (?,?)";
		super.jdbcTemplate.batchUpdate(sql2, new BatchPreparedStatementSetter() {
			
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setString(1, roleId);  
                ps.setString(2, list.get(i).getId());  
				
			}
			
			@Override
			public int getBatchSize() {
				return list.size();
			}
		});
		
	}

	@Override
	public void batchUpdateRoleAndOffice(final String roleId, final List<Office> list) {
		//1: delete 
		String sql1 = "delete from sys_role_office where role_id=?";
		super.jdbcTemplate.update(sql1, roleId);
		//2: insert
		String sql2 = "insert into sys_role_office (role_id, office_id) values (?,?)";
		super.jdbcTemplate.batchUpdate(sql2, new BatchPreparedStatementSetter() {
			
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setString(1, roleId);  
                ps.setString(2, list.get(i).getId());  
				
			}
			
			@Override
			public int getBatchSize() {
				return list.size();
			}
		});
		
	}

	@Override
	public int deleteRoleAndUser(String roleId, String userId) {
		String sql = "delete from sys_user_role where role_id=? and user_id=?";
		return super.update(sql, roleId, userId);
	}
	
	@Override
	public int addRoleAndUser(String roleId, String userId) {
		String sql = "insert into sys_user_role (user_id, role_id) values(?,?)";
		return super.update(sql, roleId, userId);
	}

}
